#!/usr/bin/env bash
#
# Runs clang-format on changed regions before commit.
#
# To install this, copy it to .git/hooks/pre-commit in your repo.
# Remaining installation checks/instructions will be printed when you commit.
#

read -d '' help <<- EOF
  This repository requires you to install the git clang-format command.
  One-time setup steps:
    1) install the git-clang-format script in your \$PATH, for example:
      curl https://raw.githubusercontent.com/llvm-mirror/clang/master/tools/clang-format/git-clang-format > /usr/local/bin/git-clang-format
    2) make sure git-clang-format is executable:
      chmod u+x /usr/local/bin/git-clang-format
  In each repository where you use clang-format, add git config keys
  so that git clang-format finds your version and config:
      git config clangFormat.binary  node_modules/.bin/clang-format
      git config clangFormat.style   file
EOF

check_clang_format() {
  if hash git-clang-format 2>/dev/null; then
    return
  else
    echo "SETUP ERROR: no git-clang-format executable found, or it is not executable"
    echo "$help"
    exit 1
  fi
}

check_git_config() {
  if [[ "$(git config --get clangFormat.binary)" == "" ]]; then
    echo "SETUP ERROR: git config clangFormat.binary is wrong."
    echo "$help"
    exit 1
  elif [[ "$(git config --get clangFormat.style)" != "file" ]]; then
    echo "SETUP ERROR: git config clangFormat.style is wrong."
    echo "$help"
    exit 1
  fi
}

check_clang_format
check_git_config

readonly out=$(git clang-format -v --diff)

if [[ "$out" == *"no modified files to format"* ]]; then exit 0; fi
if [[ "$out" == *"clang-format did not modify any files"* ]]; then exit 0; fi

# echo "out: $out"
files=()
for file in `git diff --cached --name-only --diff-filter=ACMRT | grep -E "\.(cpp|hpp)$"`; do
  if ! cmp -s <(git show :${file}) <(git show :${file}|clang-format); then
    files+=("${file}")
  fi
done

# echo "out: $files"
if [ -n "${files}" ]; then
  echo "Format error within the following files:"
  printf "%s\n" "${files[@]}"
  echo "Running 'git clang-format' on your ached files:"
  readonly gcf=$(git clang-format -v --diff)
  if [[ "$gcf" == *"no modified files to format"* ]]; then
    echo "Nothing to reformat"
    exit 0;
  fi
  if [[ "$gcf" == *"clang-format did not modify any files"* ]]; then
    echo "Reformatter did not modify"
    exit 0;
  fi

  for (( i=0; i<${#files[@]}; i++ )); do 
    srcfile=${files[$i]}
    $PWD/config/dev/run_clang_format.sh "$PWD/${srcfile}"
    if [[ $? -ne 0 ]]; then exit 1; fi
    git add "$PWD/${srcfile}"
  done
  exit 0
fi

exit 0
